/***************************************************
 ** @Desc : This file for 批量充值
 ** @Time : 2019.05.15 9:34
 ** @Author : Joker
 ** @File : bulk_recharge
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.05.15 9:34
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"encoding/json"
	"github.com/tealeg/xlsx"
	"mime/multipart"
	"path"
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"recharge/utils/interface_config"
	"strconv"
	"strings"
)

type BulkRecharge struct {
	KeepSession
}

// 展示批量充值页面
// @router /merchant/show_bulk_recharge_ui/ [get,post]
func (the *BulkRecharge) ShowBulkRechargeUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}
	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.TplName = "bulk_recharge.html"
}

// 批量充值
// @router /merchant/do_bulk_recharge/?:params [post]
func (the *BulkRecharge) DoBulkRecharge() {
	userId := the.GetSession("userId").(int)

	money := strings.TrimSpace(the.GetString("all_amount"))
	allRecords := strings.TrimSpace(the.GetString("all_records"))
	file, header, err := the.GetFile("file")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	if err != nil {
		msg = "请上传批量文件! " + err.Error()
	} else {

		msg0, verify := payImpl.VerificationBulkRechargeInfo(money, allRecords)
		if verify {

			msg, flag = handleRechargeFile(header, file, msg, allRecords, the, userId, flag)
		} else {
			msg = msg0
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

func handleRechargeFile(header *multipart.FileHeader, file multipart.File, msg string, allRecords string, the *BulkRecharge, userId int, flag int) (string, int) {
	fileName := header.Filename
	defer file.Close()
	split := strings.Split(fileName, ".")
	if len(split) < 2 {
		msg = "请上传批量文件!"
	} else {

		fileType := split[1]
		if strings.Compare(strings.ToLower(fileType), "xls") != 0 &&
			strings.Compare(strings.ToLower(fileType), "xlsx") != 0 {
			msg = "仅支持“xls”、“xlsx”格式文件!"
		} else {
			b, _ := strconv.Atoi(allRecords) //循环记录数

			//重命名文件
			fileName = split[0] + " - " + globalMethod.GetNowTimeV2() + globalMethod.RandomString(4) + ".xlsx"

			//保存文件
			filePath := "static/excel/recharge/"
			_ = the.SaveToFile("file", path.Join(filePath, fileName))

			//读取文件内容
			xlFile, err := xlsx.OpenFile(filePath + fileName)
			if err != nil {
				msg = "文件内容错误！"
			} else {

				msg, flag = handleRechargeFileContent(xlFile, userId, msg, flag, b)
			}
		}
	}
	return msg, flag
}

func handleRechargeFileContent(xlFile *xlsx.File, userId int, msg string, flag int, b int) (string, int) {
	sheet := xlFile.Sheets[0]
	//只读取文档中第一个工作表，忽略其他工作表
	for k, row := range sheet.Rows {
		if k == 0 || k == 1 { //忽略第一、二行数据
			continue
		}

		//出现空行，则忽略后面记录
		if row.Cells[0].String() == "" || row.Cells[3].String() == "" {
			break
		}

		XFMerchant := merchantFactor.QueryOneMerchantForRecharge()

		record := models.RechargeRecord{}
		record.UserId = userId
		record.MerchantNo = XFMerchant.MerchantNo

		record.SerialNumber = utils.XF + globalMethod.GetNowTimeV2() + globalMethod.RandomString(10)
		record.ReOrderId = utils.XF + globalMethod.GetNowTimeV2() + globalMethod.RandomString(8)
		record.ReAccountName = strings.TrimSpace(row.Cells[0].String()) //收款方户名
		record.ReAccountNo = strings.TrimSpace(row.Cells[1].String())   //收款方账号
		record.ReCertificateType = "0"
		record.ReRecevieBank = "NUCC"

		record.NoticeUrl = interface_config.XF_RECHANGE_NOTICE_URL + record.ReOrderId

		amount := strings.TrimSpace(row.Cells[3].String()) //金额
		//金额不正确，此条记录不通过
		verify := payImpl.VerificationBulkRechargeMoney(amount)
		if !verify {
			continue
		}

		yuanToFloat, _ := globalMethod.MoneyYuanToFloat(amount)
		record.ReAmount = yuanToFloat
		record.Status = utils.I

		// 多通道代付
		switch XFMerchant.ChannelType {
		case utils.XF:
			//先锋
			record.RecordType = utils.XF

			// 4.0.0版本
			//result, err := xfRecharge(record, XFMerchant.SecretKey)

			// 5.0.0版本
			encode := encrypt.EncodeMd5([]byte(globalMethod.RandomString(32)))
			result, err := xfRechargeV2(record, encode, XFMerchant.SecretKey)
			if err != nil {
				msg = err.Error()
			} else {

				resp := models.XFPayResponseBody{}
				err = json.Unmarshal(result, &resp)
				if err != nil {
					sys.LogError("第", k+1, "条", "先锋充值响应数据格式错误:", err)
				} else {

					if strings.Compare("00000", resp.ResCode) != 0 {
						sys.LogDebug("第", k+1, "条", "先锋充值错误:", resp)
					} else {

						nowTime := globalMethod.GetNowTime()
						record.CreateTime = nowTime
						record.EditTime = nowTime
						record.Remark = resp.ResMessage

						// 添加充值记录
						flag, _ = rechargeMdl.InsertRechargeRecord(record)
					}
				}
			}
		}

		if k == b+1 || k == 999 { //数据行数不得多于1000行
			break
		}
	}
	return msg, flag
}
